/*
 * $Id: BatchReRegistrationController.java,v 1.4 2012/04/29 21:59:36 navdeep_mahajan Exp $
 *
 * Copyright (C) 2010 General Electric Company. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 *
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

package com.ge.healthcare.autosc.ui.assetReg.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.healthcare.autosc.ui.assetReg.domain.FileUploadBean;
import com.ge.healthcare.autosc.ui.assetReg.domain.SblAssetRegFailRec;
import com.ge.healthcare.autosc.ui.assetReg.service.AssetRegistrationHelper.RegistrationType;
import com.ge.healthcare.autosc.ui.assetReg.service.FailureRecordManager;

public class BatchReRegistrationController extends SimpleFormController {

	FailureRecordManager failureRecordMananger;

	public FailureRecordManager getFailureRecordMananger() {
		return failureRecordMananger;
	}

	public void setFailureRecordMananger(
			FailureRecordManager failureRecordMananger) {
		this.failureRecordMananger = failureRecordMananger;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Map<String, Object> myModel = new HashMap<String, Object>();
		List<String> registrationStatus = new ArrayList<String>();
		int counter = 0;
		int failCounter = 0;
		request.setAttribute("noResult", false);
		// start processing the file uploaded by user .
		FileUploadBean bean = (FileUploadBean) command;
		String file = bean.getFile();
		ASCLogger.info(this.getClass(), "onSubmit", "Received file:" + file);
		if (file == null) {
			registrationStatus
					.add("\nFile could not be Processed. Please verify File location...\n");
		} else if (file.equals("")) {
			registrationStatus
					.add("\nFile could not be Processed. No System Ids found in the File\n");
		} else {
			registrationStatus.add("\nReading file information completed \n");
			// get the rows of data
			String[] systemRows = file.split("\n");
			int systemRecorsLength = systemRows.length;
			ASCLogger.info(this.getClass(), "onSubmit", "Number of Lines in file:" + systemRecorsLength);
			int index = 0;
			while (index < systemRecorsLength) {
				// skip first row as it contains the headers
				if (index == 0) {
					index++;
					continue;
				}
				// split the data in each row into appropriate format as decided
				ASCLogger.info(this.getClass(), "onSubmit", "Proceessing line:" + systemRows[index]);
				String[] recordFields = systemRows[index].split(",");
				try {
					// first column contains the systemId
					String systemId = recordFields[0];
					// second column contains connection type
					String connType = recordFields[1];
					String failureDate = null;
					if (recordFields.length > 2){
					// third column contains failure date
						failureDate = recordFields[2];
					}
					String contextId = null;
					if (recordFields.length > 3){
						// fourth colum contains context id
						contextId = recordFields[3];
					}
					String contextName = null;
					if (recordFields.length > 4){
					// fifth column contains context name
					contextName = recordFields[4];
					}
					try {
						SblAssetRegFailRec record = new SblAssetRegFailRec();
						record.setSystemId(systemId);
						record.setConnType(connType);
						if (!ASCUtil.isNullOrEmpty(failureDate)) {
							record.setFailureDate(new SimpleDateFormat(
									"MM/dd/yyyy").parse(failureDate));
						} else {
							record.setFailureDate(new Date());
						}
						if (!ASCUtil.isNullOrEmpty(contextId)) {
							record.setRemoteAccessInfo(contextId + "<SEP>"
									+ contextName);
						}
						failureRecordMananger.registerAndRemoveRecord(record,
								RegistrationType.BatchRegistration);
						registrationStatus.add(systemId + " Success \n");
						counter++;
						ASCLogger.info(this.getClass(), "onSubmit",
								"Registration successful for:" + systemId);
					} catch (Exception e) {
						failCounter++;
						registrationStatus.add(systemId + " Failed. Reason: "
								+ e.getMessage() + "\n");
						ASCLogger.error(this.getClass(), "onSubmit",
								"Failed Registration for systemId:" + systemId,
								e);
					}
				} catch (Exception e) {
					failCounter++;
					registrationStatus
							.add("Error parsing the row. Please check the sample csv file for the valid format.\n");
					ASCLogger.error(this.getClass(), "onSubmit",
							"Failed to parse the row", e);
				}

				index++;
			}

			registrationStatus.add(counter + " of " + (systemRows.length - 1)
					+ " Asset Id successfully registered.\n");
			registrationStatus.add(failCounter + " of "
					+ (systemRows.length - 1)
					+ " Asset Id failed registration.");
		}
		myModel.put("status", registrationStatus);
		return new ModelAndView("batchRegister", "model", myModel);
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(String.class,
				new StringMultipartFileEditor());
		request.setAttribute("noResult", true);
	}
}
